package com.pinyougou.sellergoods.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pinyougou.common.pojo.PageResult;
import com.pinyougou.mapper.*;
import com.pinyougou.pojo.*;
import com.pinyougou.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品服务接口实现类
 *
 * @author lee.siu.wah
 * @version 1.0
 * <p>File Created at 2019-09-24<p>
 */
@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsDescMapper goodsDescMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemCatMapper itemCatMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SellerMapper sellerMapper;

    @Override
    public void save(Goods goods) {
        try{
            // 1. 往tb_goods插入数据
            goods.setAuditStatus("0");
            goodsMapper.insertSelective(goods);


            // 2. 往tb_goods_desc插入数据
            // 设置主键列
            goods.getGoodsDesc().setGoodsId(goods.getId());
            goodsDescMapper.insertSelective(goods.getGoodsDesc());


            // 3. 往tb_item插入数据
            // 判断是否用规格
            if ("1".equals(goods.getIsEnableSpec())) { // 启用
                for (Item item : goods.getItems()) {
                    // item : {spec:{}, price:0, num:9999, status:'0', isDefault:'0'}
                    // SKU商品标题 = SPU商品名称 + spec ({"网络":"电信4G","机身内存":"128G"})
                    Map<String, String> specMap = JSON.parseObject(item.getSpec(), Map.class);
                    StringBuilder title = new StringBuilder(goods.getGoodsName());
                    //  Apple iPhone 11 Pro (A2217) 512GB 金色
                    for (String value : specMap.values()) {
                        title.append(" " + value);
                    }
                    item.setTitle(title.toString());

                    // 设置SKU商品其它的信息
                    setItemInfo(goods, item);

                    itemMapper.insertSelective(item);
                }
            }else { // 没启用
                // SPU就是SKU
                /** 创建SKU具体商品对象 */
                Item item = new Item();
                /** 设置SKU商品的标题 */
                item.setTitle(goods.getGoodsName());
                /** 设置SKU商品的价格 */
                item.setPrice(goods.getPrice());
                /** 设置SKU商品库存数据 */
                item.setNum(9999);
                /** 设置SKU商品启用状态 */
                item.setStatus("1");
                /** 设置是否默认*/
                item.setIsDefault("1");
                /** 设置规格选项 */
                item.setSpec("{}");

                // 设置SKU商品其它的信息
                setItemInfo(goods, item);

                itemMapper.insertSelective(item);
            }

        }catch (Exception ex){
            throw new RuntimeException(ex);
        }
    }

    /** 设置SKU商品其它的信息 */
    private void setItemInfo(Goods goods, Item item){
        // SKU商品图片
        // [{"color":"金色","url":"http://image.pinyougou.com/jd/wKgMg1qtKEOATL9nAAFti6upbx4132.jpg"},
        // {"color":"深空灰色","url":"http://image.pinyougou.com/jd/wKgMg1qtKHmAFxj7AAFZsBqChgk725.jpg"},
        // {"color":"银色","url":"http://image.pinyougou.com/jd/wKgMg1qtKJyAHQ9sAAFuOBobu-A759.jpg"}]
        List<Map> imageList = JSON.parseArray(goods.getGoodsDesc().getItemImages(), Map.class);
        if (imageList != null && imageList.size() > 0) {
            item.setImage(imageList.get(0).get("url").toString());
        }
        // SKU商品三级分类id
        item.setCategoryid(goods.getCategory3Id());
        // SKU商品创建时间
        item.setCreateTime(new Date());
        // SKU商品修改时间
        item.setUpdateTime(item.getCreateTime());
        // SKU商品关联的SPU的id
        item.setGoodsId(goods.getId());
        // SKU商品商家id
        item.setSellerId(goods.getSellerId());

        // SKU商品三级分类名称
        ItemCat itemCat = itemCatMapper.selectByPrimaryKey(goods.getCategory3Id());
        item.setCategory(itemCat != null ? itemCat.getName() : "");
        // SKU商品品牌
        Brand brand = brandMapper.selectByPrimaryKey(goods.getBrandId());
        item.setBrand(brand != null ? brand.getName() : "");
        // SKU商品店铺名称
        Seller seller = sellerMapper.selectByPrimaryKey(goods.getSellerId());
        item.setSeller(seller != null ? seller.getNickName() : "");
    }

    @Override
    public void update(Goods goods) {

    }

    @Override
    public void delete(Serializable id) {

    }

    @Override
    public void deleteAll(Serializable[] ids) {

    }

    @Override
    public Goods findOne(Serializable id) {
        return null;
    }

    @Override
    public List<Goods> findAll() {
        return null;
    }

    @Override
    public PageResult findByPage(Goods goods, Integer page,Integer rows) {
        try{
           // 开启分页
           PageInfo<Map<String,Object>> pageInfo = PageHelper.startPage(page, rows)
                   .doSelectPageInfo(new ISelect() {
               @Override
               public void doSelect() {
                    goodsMapper.findAll(goods);
               }
           });

           List<Map<String,Object>> goodsList = pageInfo.getList();
           goodsList.forEach(map -> {
               // 获取三级分类id
               Long category3Id = (Long)map.get("category3Id");
               if (category3Id != null){
                   // 查询一级分类名称
                   String category1Name = itemCatMapper.selectByPrimaryKey(map.get("category1Id")).getName();
                   map.put("category1Name",category1Name);

                   // 查询二级分类名称
                   String category2Name = itemCatMapper.selectByPrimaryKey(map.get("category2Id")).getName();
                   map.put("category2Name",category2Name);

                   // 查询三级分类名称
                   String category3Name = itemCatMapper.selectByPrimaryKey(map.get("category3Id")).getName();
                   map.put("category3Name",category3Name);
               }

           });

           return new PageResult(pageInfo.getPages(), goodsList);
        }catch (Exception ex){
           throw new RuntimeException(ex);
        }
    }

    /** 修改商品状态 */
    public void updateStatus(String columnName, Long[] ids, String status){
        try{
            // UPDATE tb_goods SET audit_status = ? WHERE id IN(?,?,?)
            goodsMapper.updateStatus(columnName, ids, status);
        }catch (Exception ex){
            throw new RuntimeException(ex);
        }
    }

    /*获取商品信息(FreeMarker)*/
    @Override
    public Map<String, Object> getGoods(Long goodsId) {
        //定义数据模型
        Map<String,Object>dataModel = new HashMap<>();
        try {
            /*加载商品的SPU数据*/
            Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
            dataModel.put("goods",goods);
            /*加载商品描述数据*/
            GoodsDesc goodsDesc = goodsDescMapper.selectByPrimaryKey(goodsId);
            dataModel.put("goodsDesc",goodsDesc);
            /*商品分类*/
            if(goods != null && goods.getCategory3Id()!=null){
                String itemCat1 = itemCatMapper.selectByPrimaryKey(goods.getCategory1Id()).getName();
                String itemCat2 = itemCatMapper.selectByPrimaryKey(goods.getCategory2Id()).getName();
                String itemCat3 = itemCatMapper.selectByPrimaryKey(goods.getCategory3Id()).getName();
                dataModel.put("itemCat1",itemCat1);
                dataModel.put("itemCat2",itemCat2);
                dataModel.put("itemCat3",itemCat3);
            }
            //商品查询
            //查询SKU数据
           Example example = new Example(Item.class);
            //创造查询条件对象
            Example.Criteria criteria = example.createCriteria();
            //状态码为1的
            criteria.andEqualTo("status","1");
            //根据id查
            criteria.andEqualTo("goodsId",goodsId);
            //是否默认排序(保证默认第一个为默认)
            example.orderBy("isDefault").desc();
            //根据条件查询SKU商品数据
            List<Item> itemList = itemMapper.selectByExample(example);
            dataModel.put("itemList",JSON.toJSONString(itemList));

            return dataModel;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public List<Item> findItemByGoodsId(List<Long> ids) {
        //创建示范对象
        Example example = new Example(Item.class);
        //创建 查询条件对象
        Example.Criteria criteria = example.createCriteria();
        //添加IN条件
        criteria.andIn("goodsId",ids);
        //查询数据
        return itemMapper.selectByExample(example);
    }
}
